package GameLogic

import (
	"PBMessage"

	"time"

	"git.oschina.net/yangdao/extlib/log"
	"git.oschina.net/yangdao/extlib/math3d"
	"github.com/golang/protobuf/proto"
)

type runState struct {
	*genericState
}

func (run *runState) onEnter(args ...interface{}) {
	run.gameUnit.isMoveing = true
	state := &PBMessage.SC_UnitState{}
	state.UnitId = proto.Int64(run.gameUnit.Unit.GUID)
	state.Time = proto.Int64(time.Now().UnixNano() / 1e6)
	state.State = proto.Int32(1)
	state.IntP0 = proto.Int32(int32(run.gameUnit.targetPos.X))
	state.IntP1 = proto.Int32(int32(run.gameUnit.targetPos.Z))
	run.gameUnit.Scene.(*GameScene).sendEachPlayer(PBMessage.PBID_SC_UnitState, state)
	log.Log("GameLogic,Info", "单位进入移动状态")
}

func (run *runState) onUpdate(dt int) {
	run.gameUnit.setPos(&run.gameUnit.preMovePos, time.Now().UnixNano()/1e6, run.gameUnit.startMoveTime,
		run.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
	cmd, tuple := run.gameUnit.getCommond()
	switch cmd {
	case CMD_MOVE:
		state := tuple[3].(int32)
		if state == 0 {
			run.gameUnit.isMoveing = false
			run.gameUnit.setPos(&run.gameUnit.preMovePos, tuple[4].(int64), run.gameUnit.startMoveTime,
				run.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
			run.gameUnit.startMoveTime = 0

			run.gameUnit.chageState("idle")
		} else {
			run.gameUnit.isMoveing = true
			run.gameUnit.setPos(&run.gameUnit.preMovePos, tuple[4].(int64), run.gameUnit.startMoveTime,
				run.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
			run.gameUnit.Unit.Dir = math3d.Vec3{X: float64(tuple[1].(int32)), Y: 0, Z: float64(tuple[2].(int32))}
			run.gameUnit.Unit.Dir.Normalize()
			run.gameUnit.startMoveTime = tuple[4].(int64)
			run.gameUnit.preMovePos = run.gameUnit.Unit.Pos()

		}
	case CMD_RUNABILITY:
		run.gameUnit.Unit.CurAbility = run.gameUnit.Unit.Abilitys[tuple[1].(string)]
		if run.gameUnit.Unit.CurAbility.Base().IsCanCast() {
			run.gameUnit.chageState("canRunAbility")
		}
	case CMD_SPEEDCHANGE:
		nowTime := time.Now().UnixNano() / 1e6
		run.gameUnit.setPos(&run.gameUnit.preMovePos, nowTime, run.gameUnit.startMoveTime, run.gameUnit.Speed)
		run.gameUnit.preMovePos = run.gameUnit.Pos()
		run.gameUnit.startMoveTime = nowTime
		run.gameUnit.Speed = run.gameUnit.GetProperty(":MoveSpeed").(int)
		move := run.gameUnit.toSCMove(run.gameUnit.startMoveTime, run.gameUnit.Speed, &run.gameUnit.Dir)
		run.gameUnit.Scene.(*GameScene).sendEachPlayer(PBMessage.PBID_SC_MoveUnit, move)
	}
}
